import { Provide } from '@midwayjs/decorator';
// import { IUserOptions } from '../interface';
import { User } from '../entity/user';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository, Like } from 'typeorm';
import { UserDTO } from '../dto/user';
const bcrypt = require('bcryptjs');
// import bcrypt from 'bcryptjs';
import { BaseService } from './base';
@Provide()
export class UserService extends BaseService {
  @InjectEntityModel(User)
  userModel: Repository<User>;

  checkPassword(pass: string, userpass: string, salt: string) {
    // 生成随机字符串 gen => generate 生成 salt 码
    // const salt = bcrypt.genSaltSync(10);
    // 使用随机字符串对密码进行加密
    const password = bcrypt.hashSync(pass, salt);
    // return true;
    console.log(pass, password, userpass);
    // throw new Error({ pass, password, userpass } + '');

    if (password === userpass) {
      return true;
    }
    return false;
  }

  async page(name: string, page: number = 1) {
    console.log(page, 111);
    return await this.pagination(
      this.userModel,
      {
        select: [
          'id',
          'username',
          'name',
          'create_time',
          'update_time',
          'email',
        ],
        where: name
          ? [{ username: Like(`%${name}%`) }, { name: Like(`%${name}%`) }]
          : '',
        order: {
          update_time: 'DESC',
        },
      },
      page
    );
  }

  // find
  async getUserInfoByLogin(user: UserDTO) {
    const username = user.username;
    const find = await this.userModel.findOne({ username });
    if (!find) {
      throw new Error('用户名或密码错误');
    }

    if (!this.checkPassword(user.password, find.password, find.salt)) {
      throw new Error('用户名或密码错误');
    }

    return find;
  }

  async addUser(user: UserDTO) {
    const username = user.username;
    const find = await this.userModel.findOne({ username });
    if (find) {
      throw new Error('相同用户名用户已存在');
    }
    // 生成随机字符串 gen => generate 生成 salt 码
    const salt = bcrypt.genSaltSync(10);
    // 使用随机字符串对密码进行加密
    user.password = bcrypt.hashSync(user.password, salt);

    const res = await this.userModel.save(Object.assign(user, { salt: salt }));
    return res.id;
  }

  async updateUser(updateUser: UserDTO) {
    const id = updateUser.id;
    const find = await this.userModel.findOne({ id });
    if (!find) {
      throw new Error('用户不存在');
    }
    find.name = updateUser.name;
    // // 生成随机字符串 gen => generate 生成 salt 码
    // const salt = bcrypt.genSaltSync(10);
    // // 使用随机字符串对密码进行加密
    // find.password = bcrypt.hashSync(updateUser.password, salt);
    const res = await this.userModel.save(find);
    return res;
  }

  async deleteUser(user: UserDTO) {
    const id = user.id;
    const find = await this.userModel.findOne({ id });
    if (!find) {
      throw new Error('用户不存在');
    }
    const res = await this.userModel.remove(find);
    return res;
  }
}
